<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>在线聊天室</title>
  <!-- <script src="01service.js"></script> -->

</head>
<body>
  <div id="listContainer"></div>
  <div id="msg"></div>
  <input type="text" id="text">
  <input type="button" value="发送" onclick="send()">
  

  <script>
    var websocket = new WebSocket('ws://127.0.0.1:8080')

    // readyState 
    // 0 连接还没有建立 （正在建立连接）
    // 1 连接建立成功
    // 2 连接正在关闭
    // 3 连接已经关闭

    var arrList = []

    websocket.onopen = function() {
      console.log('-----------',websocket.readyState)      
    }

    function send() {
      var text = document.getElementById('text').value
      websocket.send(text)
    }

    websocket.onmessage = function(msg) {
      console.log('----接受到服务端发送过来的数据----',msg.data)
      arrList.push(msg.data)
      updateList() 
    }

    function updateList() {
      var container = document.getElementById('listContainer');
      container.innerHTML = ''; // 清空容器
      arrList.forEach(function(item) {
        var div = document.createElement('div');
        div.textContent = item;
        container.appendChild(div);
   });
  }


      
  </script>


</body>
</html>